const router = require('express').Router();
const Movie = require('../../models/movie');
const {
    route
} = require('..');

router.get('/', async (req, res) => {
    //  render直接进入的就是views目录下 ，不要在admin前写../ 也不要在index后面添加后缀名.ejs
    const page = req.query.page * 1 || 1;
    const per = req.query.per * 1 || 10;
    const queryBuild = {};
    if (req.query.title) {
        queryBuild.title = new RegExp(req.query.title);
    }
    const movies = await Movie.find(queryBuild)
        .skip((page - 1) * per)
        .limit(per)
        .sort({
            _id: -1
        });
    const totals = await Movie.count(queryBuild);
    res.render('admin/movies/index', {
        movies,
        totals,
        page,
        pages: Math.ceil(totals / per),
    });
});
router.get('/new', (req, res) => {
    res.render('admin/movies/new');
});

router.post('/create', async (req, res) => {
    const movie = new Movie(req.body);
    await movie.save();
    res.redirect('/admin/movies');
});

router.get('/edit/:id', async (req, res) => {
    const movie = await Movie.findById(req.params.id);
    res.render('admin/movies/edit', {
        movie,
    });
});

router.post("/modify/:id", async (req, res) => {
    await Movie.findByIdAndUpdate(req.params.id, req.body);
    res.redirect("/admin/movies");
});

router.post('/remove', async (req, res) => {
    await Movie.findByIdAndDelete(req.body.removeInput);
    res.redirect('/admin/movies');
});

module.exports = router;